const dgram = require("dgram");
const sysTool = require('../tool/sys')


const configTool = require('../tool/config')

module.exports = class UdpServer {

  
  netInfo = {
    networkInterfaces: [],
    broadCastInfo: {}
  }

  obj = null
  static getInstant(){
    if (!this.obj) {
      this.obj = new UdpServer()
    }
    return this.obj
  }

  init() {
    this.broadCast()
  }  

  setBroadCastInfo(data) {
    configTool.set('broadCastIp', data.ip)
    this.netInfo.broadCastInfo.ip = data.ip
    this.netInfo.broadCastInfo.netname = data.name
  }

  // 广播ip信息
  async broadCast() {
    let sysInfo = await sysTool.getOsInfo()
    let netInfo = await sysTool.getNetworkInterfaces()
    this.netInfo.networkInterfaces = netInfo

    let setNet = netInfo[0]
    let ipCfg = configTool.get('broadCastIp')
    if (ipCfg) {
      netInfo.map(v => {
        if (v.ip == ipCfg) {
          setNet = v
        }
      })
    }

    this.netInfo.broadCastInfo = {
      ip: setNet.ip,
      hostname: sysInfo.hostname,
      netname: setNet.name
    }
   
    
    var socket = dgram.createSocket("udp4");

    socket.bind(function () {
      socket.setBroadcast(true);
    });

    setInterval(()=>{
      let broadData = `alin|${this.netInfo.broadCastInfo.hostname}|${this.netInfo.broadCastInfo.ip}`
      socket.send(broadData, 0, broadData.length, 41234, '255.255.255.255', (err, bytes)=>{ });
    }, 5000)
  }

}